package com.thinkit.bigdata.web.controller.cronTask;

import com.thinkit.bigdata.core.util.DateFormatUtil;
import com.thinkit.bigdata.core.util.FileUtil;
import com.thinkit.bigdata.core.util.FtpUtil;
import com.thinkit.bigdata.core.util.ProjectPubMet;
import com.thinkit.bigdata.web.coremet.SystemStatic;
import com.thinkit.bigdata.web.model.BaseEntity;
import com.thinkit.bigdata.web.model.bus.BusVoiceDetails;
import com.thinkit.bigdata.web.model.bus.BusVoiceDetailsExample;
import com.thinkit.bigdata.web.model.result.Constants;
import com.thinkit.bigdata.web.model.sys.SysExportUserParam;
import com.thinkit.bigdata.web.model.sys.SysExportUserParamExample;
import com.thinkit.bigdata.web.service.bus.BusVoiceDetailsService;
import com.thinkit.bigdata.web.service.sys.SysConfigService;
import com.thinkit.bigdata.web.service.sys.SysExportUserParamService;
import org.apache.log4j.Logger;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Date;
import java.util.List;

/**
 * 文件过期相关操作
 */
@Component
public class FileOverdueCronTask {

    private static Logger logger = Logger.getLogger(FileOverdueCronTask.class);

    @Resource
    private BusVoiceDetailsService detailsService;

    @Resource
    private SysExportUserParamService paramService;

    @Resource
    private SysConfigService sysConfigService;

    @Resource
    private ProjectPubMet pubMet;

    /**
     * 详情页，听取语音后，下载的文件，每天一删除
     */
    @Scheduled(cron = "0 0 0 * * ?")
    public void cronLocalAudioDel() {
        String logTxt = "【删除本地音频任务】";
        logger.info(logTxt + "启动");
//        boolean start = true;
//        try {
//            start = FtpUtil.sendCcs("cronDelAudioTask", logTxt);
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        if (!start) {
//            logger.info(logTxt + "该方法其他机器有启动");
//            return;
//        }
        String localPath = SystemStatic.SYSTEM_USER_PATH_AUDIO;
        logger.info(logTxt + "删除路径: " + localPath);
        FileUtil.deleteDirectory(localPath);
    }

    /**
     * 删除过期的话务明细导出，审批导出的excel文件
     */
    @Scheduled(cron = "0 0 4 * * ?")
    public void cronLocalExcelDel() {
        try {
            String logTxt = "【删除失效excel文件任务】";
            logger.info(logTxt + "启动");
            if (!FtpUtil.sendCcs("cronDelExportTask", logTxt)) {
                logger.info(logTxt + "该方法其他机器有启动");
                return;
            }
            //登陆ftp
            FtpUtil ftpUtil = pubMet.getFtpUtil();
            int textMaxHour = Integer.parseInt(sysConfigService.sysConfigGetByPK(Constants.TEXT_MAX_HOUR).getValue());
            //查询话务明细导出的过期excel文件
            BusVoiceDetailsExample detailsExample = new BusVoiceDetailsExample();
            detailsExample.createCriteria().andIsdelEqualTo(BaseEntity.FILE_IS_DEL_NO)
                    .andStatusEqualTo(BaseEntity.VOICE_EXPORT_YES);
            List<BusVoiceDetails> details = detailsService.selectByExample(detailsExample);
            for (BusVoiceDetails detail : details) {
                //当前时间 - 过期时间 = 文件完成时间过期的时间
                Date invalidTime = DateFormatUtil.addMinute(detail.getFinishtime(), (textMaxHour * 60));
                if (DateFormatUtil.intervalSecond(invalidTime,  new Date()) > 0) {
                    logger.info(logTxt + "话务明细导出的过期excel文件【id = " + detail.getId() + "】");
                    if (ftpUtil.deleteFile(detail.getFilepath())) {
                        logger.info(logTxt + "【filePath = " + detail.getFilepath() + "】文件删除成功，修改状态为【文件已删除】");
                        detail.setIsdel(BaseEntity.FILE_IS_DEL_YES);
                        String log = detailsService.updateByPrimaryKey(detail).getCode() == 0 ? "状态修改失败" : "状态修改成功";
                        logger.info(logTxt + log);
                    } else {
                        logger.info(logTxt + "【filePath = " + detail.getFilepath() + "】文件删除失败");
                    }
                }
            }
            //查询审批导出的过期excel文件
            SysExportUserParamExample paramExample = new SysExportUserParamExample();
            detailsExample.createCriteria().andIsdelEqualTo(BaseEntity.FILE_IS_DEL_NO)
                    .andStatusEqualTo(BaseEntity.VOICE_EXPORT_YES);
            List<SysExportUserParam> params = paramService.selectByExample(paramExample);
            for (SysExportUserParam param : params) {
                //当前时间 - 过期时间 = 文件完成时间过期的时间
                Date invalidTime = DateFormatUtil.addMinute(param.getFinishtime(), (textMaxHour * 60));
                if (DateFormatUtil.intervalSecond(invalidTime,  new Date()) > 0) {
                    logger.info(logTxt + "审批导出过期excel文件【id = " + param.getProvaltaskid() + "】");
                    if (ftpUtil.deleteFile(param.getFileurl())) {
                        logger.info(logTxt + "【filePath = " + param.getFileurl() + "】文件删除成功，修改状态为【文件已删除】");
                        param.setIsdel(BaseEntity.FILE_IS_DEL_YES);
                        String log = paramService.updateByPrimaryKey(param) == 0 ? "状态修改失败" : "状态修改成功";
                        logger.info(logTxt + log);
                    } else {
                        logger.info(logTxt + "【filePath = " + param.getFileurl() + "】文件删除失败");
                    }
                }
            }
            ftpUtil.disconnect();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
